import React, { Component } from 'react'
import PubSub from 'pubsub-js'
//import axios from 'axios'

export default class Search extends Component {
  search = async ()=>{
    //获取用户的输入
    console.log(this.keyWordElement.value)
    //发送请求前，通知List更新状态
    /* this.props.updateAppState({isFirst:false,isLoading:true}) */
    PubSub.publish('ccx', {isFirst:false,isLoading:true})

    //发送网络请求
    // axios.get(`http://localhost:3000/api1/search/users?q=${this.keyWordElement.value}`).then(
    //   response => {
    //     console.log('发布消息成功了',response)
    //     /* this.props.updateAppState({isLoading:false,users:response.data.items}) */
    //     PubSub.publish('ccx', {isLoading:false,users:response.data.items})
    //   },
    //   error => {
    //     console.log('失败了',error)
    //     /* this.props.updateAppState({isLoading:false,err:error.message}) */
    //     PubSub.publish('ccx', {isLoading:false,err:error.message})
    //   }
    // )

    //发送网络请求---使用fetch发送(未优化)
    // fetch(`http://localhost:3000/api1/search/users?q=${this.keyWordElement.value}`).then(
    //   response => {
    //     console.log('发布消息成功了',response)
    //     return response.json()
    //   },
    //   error => {
    //     console.log('失败了',error)
    //     return new Promise(()=>{})
    //   }
    // ).then(
    //   response => {
    //     console.log('发布消息成功了nnnn',response)
    //   },
    //   error => {
    //     console.log('失败了',error)
    //   }
    // )

    //发送网络请求---使用fetch发送(优化)
    // fetch(`http://localhost:3000/api1/search/users?q=${this.keyWordElement.value}`).then(
    //   response => {
    //     console.log('发布消息成功了',response)
    //     return response.json()
    //   }
    // ).then(
    //   response => {
    //     console.log('发布消息成功了nnnn',response)
    //   }
    // ).catch(
    //   error=>{console.log(error)}
    // )

    try {
      const response = await fetch(`http://localhost:3000/api1/search/users?q=${this.keyWordElement.value}`)
      const data = await response.json()
      console.log(data)
      PubSub.publish('ccx', {isLoading:false,users:data.items})
    } catch(error) {
      console.log(error)
      PubSub.publish('ccx', {isLoading:false,err:error.message})
    }

  }
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索Github用户</h3>
        <div>
          <input ref={c => this.keyWordElement = c} type="text" placeholder="输入关键字点击搜索"/>&nbsp;
          <button onClick={this.search}>搜索</button>
        </div>
      </section>
    )
  }
}
